<template>
  <FPage class="unit-management-container">
    <div class="unit-management-left">
      <UnitTreeComponent ref="refUnitTreeComponent" @reloadUnits="reloadUnits"
                         @selectChange="selectChange"/>
    </div>
    <div class="unit-management-right">
      <UnitManageComponent v-if="showUnitManage" @reloadUnits="reloadUnits"
                           @selectChange="unitSelectChange" @addNewUnit="addNewUnit"/>
      <GroupEditComponent v-if="showGroupManage" @reloadUnits="reloadUnits" @clearSelect="clearSelect"
                          :group="selectNode" @selectChange="unitSelectChange"/>
      <UnitEditComponent v-if="showUnitEdit" @selectChange="unitSelectChange"
                         :unit="selectNode" @reloadUnits="reloadUnits"/>
    </div>
  </FPage>
</template>
<script setup>
import FPage from '@/components/layout/FPage.vue';
import UnitTreeComponent from '@/views/system/UnitManagement/UnitTreeComponent.vue';
import {computed, onMounted, shallowRef} from 'vue';
import UnitManageComponent from './UnitManageComponent';
import {isEmpty} from '@/utils/CommonUtils';
import GroupEditComponent from '@/views/system/UnitManagement/GroupEditComponent';
import UnitEditComponent from './UnitEditComponent'

defineOptions({
  name: 'UnitManagement'
});
const refUnitTreeComponent = shallowRef();
const selectNode = shallowRef();
onMounted(() => {
  refUnitTreeComponent.value.reload();
});

function reloadUnits(callback) {
  refUnitTreeComponent.value.reload().then(() => {
    if(callback) callback();
  });
}

function unitSelectChange(_selectNode) {
  selectNode.value = _selectNode;
  refUnitTreeComponent.value.unitSelectChange(_selectNode);
}

function addNewUnit() {
  selectNode.value = {
    unitGroup: false
  }
}

function selectChange(_selectNode) {
  selectNode.value = _selectNode;
}

const showUnitEdit = computed(() => {
  if (isEmpty(selectNode.value)) return false;
  if(selectNode.value.id === 'rootNode') return false;
  return !selectNode.value.unitGroup;
})

const showGroupManage = computed(() => {
  if (isEmpty(selectNode.value)) return false;
  return selectNode.value.unitGroup;
});

const showUnitManage = computed(() => {
  if (isEmpty(selectNode.value)) return false;
  return selectNode.value.id === 'rootNode';
});

function clearSelect() {
  selectNode.value = undefined;
  refUnitTreeComponent.value.clearSelect();
}
</script>
<style>
.unit-management-container {
  display: flex;
}

.unit-management-left {
  height: 100%;
  width: 300px;
  background: white;
  overflow-y: auto;
}

.unit-management-right {
  height: 100%;
  flex: 1;
  overflow-y: auto;
}
</style>
